package com.wh.wisdomsite.xbox.server.controller.me;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.me.entity.CraneProject;
import com.wh.wisdomsite.xbox.me.service.ICraneProjectService;
import com.wh.wisdomsite.xbox.pojo.me.CraneProjectIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 起重机械配置Controller
 * @package com.wh.wisdomsite.xbox.server.controller.me
 * @author 蔡道行
 * @date 16:45 2018/8/9
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/craneProject")
public class CraneProjectController {

    private static final Log logger = LogFactory.getLog(CraneProjectController.class);

    @Autowired
    private ICraneProjectService iCraneProjectService;

    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:me_craneProject_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(){
        return "/me/craneProject/craneProjectList";
    }

    /**
     * 获取起重机械配置集合
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:me_craneProject_find")
    @RequestMapping(value = "/craneProjectList.do")
    public void craneProjectList(HttpServletResponse response, CraneProjectIn in){
        try {
            logger.info("加载起重机械配置数据列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<CraneProject> page = new Page<CraneProject>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<CraneProject> ewCraneProject = new EntityWrapper<CraneProject>();
            ewCraneProject.setEntity(new CraneProject());
            if(StringUtils.isNotEmpty(in.getCsId())){
                ewCraneProject.eq("cp.Id", in.getCsId());
            }
            if(StringUtils.isNotEmpty(in.getCsId())){
                ewCraneProject.eq("cp.csId", in.getCsId());
            }
            if(StringUtils.isNotEmpty(in.getCpName())){
                ewCraneProject.like("cp.cpName", in.getCpName());
            }
            if(StringUtils.isNotEmpty(in.getCpCode())){
                ewCraneProject.like("cp.cpCode", in.getCpCode());
            }
            if(StringUtils.isNotEmpty(in.getCpUseType())){
                ewCraneProject.eq("cp.cpUseType", in.getCpUseType());
            }
            if(StringUtils.isNotEmpty(in.getMeStatus())){
                ewCraneProject.eq("cp.meStatus", in.getMeStatus());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewCraneProject = UserUtils.setEntityWrapper(ewCraneProject, "co1", "off1", "p1");
            }
            ewCraneProject.orderBy("createDate", true);
            Page<Map<String,Object>> craneProjectPage = iCraneProjectService.getMapsPage(page, ewCraneProject);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if(craneProjectPage.getRecords().size() > 0){
                for(Map<String,Object> craneProject : craneProjectPage.getRecords()){
                    JSONObject object = new JSONObject(craneProject);
                    object.put("id",craneProject.get("cpId"));
                    if(craneProject.get("csId")!= null){
                        object.put("csId",new JSONObject(craneProject.get("csId")));
                    }
                    if(craneProject.get("prId")!= null){
                        object.put("prId",new JSONObject(craneProject.get("prId")));
                    }
                    if(craneProject.get("cpUseType")!= null){
                        object.put("cpUseType",new JSONObject(craneProject.get("cpUseType")));
                    }
                    if(craneProject.get("meStatus")!= null){
                        object.put("meStatus",new JSONObject(craneProject.get("meStatus")));
                    }
                    if(craneProject.get("onLineStatus")!= null){
                        object.put("onLineStatus",new JSONObject(craneProject.get("onLineStatus")));
                    }
                    if(craneProject.get("cpUseTypeCommonDict")!= null){
                        object.put("cpUseTypeCommonDict",new JSONObject(craneProject.get("cpUseTypeCommonDict")));
                    }
                    if(craneProject.get("meStatusCommonDict")!= null){
                        object.put("meStatusCommonDict",new JSONObject(craneProject.get("meStatusCommonDict")));
                    }
                    if(craneProject.get("onLineStatusCommonDict")!= null){
                        object.put("onLineStatusCommonDict",new JSONObject(craneProject.get("onLineStatusCommonDict")));
                    }
                    if(craneProject.get("craneStandard")!= null){
                        object.put("craneStandard",new JSONObject(craneProject.get("craneStandard")));
                    }
                    if(craneProject.get("project")!= null){
                        object.put("project",new JSONObject(craneProject.get("project")));
                    }
                    array.put(object);
                }
            }
            json.put("total",craneProjectPage.getTotal());
            json.put("rows",array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载起重机械配置数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载起重机械配置数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 起重机械配置详情
     * @param craneProjectIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:me_craneProject_view")
    @RequestMapping("/craneProjectDesc.do")
    public String craneProjectDesc(CraneProjectIn craneProjectIn, String source, HttpServletRequest request) {
        logger.info("起重机械配置详情-->>开始");
        try{
            Map<String,Object> craneProject = iCraneProjectService.getMapById(craneProjectIn.getCpId());
            if(craneProject.get("createBy") != null){
                craneProject.put("createBy", UserMapManager.getUserLoginNameInMap(craneProject.get("createBy").toString()));
            }
            if(craneProject.get("updateBy") != null){
                craneProject.put("updateBy", UserMapManager.getUserLoginNameInMap(craneProject.get("updateBy").toString()));
            }
            request.setAttribute("craneProject", craneProject);
            request.setAttribute("source", source);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            logger.info("起重机械配置详情-->>结束");
            return "/me/craneProject/craneProjectDesc";
        }
    }

    /**
     * 更新或者修改
     * @param craneProject
     * @param response
     */
    @RequiresPermissions("rules:me_craneProject_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(CraneProject craneProject,HttpServletResponse response){
        try {
            //判断方法是否已经存在,存在即更新.否则为添加
            if(StringUtils.isNotEmpty(craneProject.getCpId())){
                logger.info("修改起重机械配置-->>开始");
                craneProject.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                craneProject.setUpdateDate(new Date());
                iCraneProjectService.updateById(craneProject);
                logger.info("修改起重机械配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("起重机械配置更新成功"));

            }else {
                logger.info("添加起重机械配置-->>开始");
                craneProject.setCreateBy(UserUtils.getCurrentUser().getUsId());
                craneProject.setCreateDate(new Date());
                iCraneProjectService.insert(craneProject);
                logger.info("添加起重机械配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("起重机械配置添加成功"));

            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作起重机械配置-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除起重机械配置
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:me_craneProject_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除起重机械配置-->>开始");
            iCraneProjectService.deleteById(id);
            logger.info("删除起重机械配置-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("起重机械配置删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除起重机械配置-->>Exception" + e.getMessage());
        }
    }

     /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toCraneProject.do")
    public ModelAndView toAddActivity(String cpId, String source, HttpServletRequest request) {
        logger.info("添加修改项目跳转-->>开始");
        if(StringUtils.isNotEmpty(cpId)){
            Map<String, Object> craneProject = iCraneProjectService.getMapById(cpId);
            request.setAttribute("craneProject", craneProject);
        }
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        request.setAttribute("DefaulCompany",companyId);
        request.setAttribute("source",source);
        logger.info("添加修改项目跳转-->>开始");
        return new ModelAndView("me/craneProject/craneProjectOption");
    }

    /**
     * 获取设备编号
     * @param response
     */
    @RequestMapping(value = "/getDeviceIdList.do")
    public void getDeviceIdList(HttpServletResponse response,String prId) {
        List<CraneProject> craneProjectList = new ArrayList<CraneProject>();
        try {
            logger.info("获取设备编号-->>开始");
            EntityWrapper<CraneProject> ewCraneProject = new EntityWrapper<CraneProject>();
            ewCraneProject.setEntity(new CraneProject());
            if(StringUtils.isNotEmpty(prId)){
                ewCraneProject.eq("cp.prId",prId);
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewCraneProject = UserUtils.setEntityWrapper(ewCraneProject, "co1", "off1", "p1");
            }
            ewCraneProject.groupBy("cp.deviceId");
            craneProjectList = iCraneProjectService.selectList(ewCraneProject);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取设备编号-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(craneProjectList));
        logger.info("获取设备编号-->>结束");
    }

    /**
     * 获取起重机械设备总数
     */
    @RequestMapping("/getTotal.do")
    public void getTotal(HttpServletResponse response) {
        try {
            logger.info("获取起重机械总数->>开始");
            //设置条件
            EntityWrapper<CraneProject> ewCraneProject = new EntityWrapper<>();
            ewCraneProject.setEntity(new CraneProject());
            ewCraneProject.eq("cp.dataState", "1");
            //若不是管理员设置查询条件
            if (!UserUtils.isSysAdmin()) {
                ewCraneProject = UserUtils.setEntityWrapper(ewCraneProject, "co1", "off1", "p1");
            }
            Map<String, Object> total = iCraneProjectService.getTotal(ewCraneProject);
            JSONObject json = new JSONObject();
            Object totalNumber = total.get("totalNumber");
            json.put("totalNumber",totalNumber);
            ResManager.getJsonOut(response).print(json);
            logger.info("获取起重机械设备总数->>结束");

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}
